import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.text.*;

import bidserver.src.*;

public class BidClientServlet extends HttpServlet {

    private void generateCommonHeader(String action,
            HttpServletRequest request, HttpServletResponse response,
            PrintWriter out, HttpSession session) throws IOException,
            ServletException {
        out.println("<html><head>");
        String title = "Distributed Bidder: " + action;

        out.println("<title>" + title + "</title>");
        out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"bid.css\">");
        out.println("<link href='http://fonts.googleapis.com/css?family=Candal' rel='stylesheet' type='text/css'>");
        out.println("<link href='http://fonts.googleapis.com/css?family=Crimson+Text' rel='stylesheet' type='text/css'>");
        
        out.println("</head>");
        out.println("<body bgcolor=\"white\">");
        out.println("<h1>" + title + "</h1>");
    }

    private void generateCommonFooter(HttpServletRequest request,
            HttpServletResponse response, PrintWriter out, HttpSession session,
            String serverHost, int serverPort)
            throws IOException, ServletException {
        String storedName = (String) session.getAttribute("username");
        out.print("<hr>Logged in as: " + storedName + "    ");
        out.print("<a href=\"?action=logout\">[Logout]</a>");
        out.print("<a href=\"?action=auctionlist\">[Auction List]</a>");
        if (serverHost != null) {
            out.print("<br/>Used Bid Server: " + serverHost + ":" + serverPort);
        }

        out.println("</body>");
        out.println("</html>");
    }

    private void doLogin(HttpServletRequest request,
            HttpServletResponse response, PrintWriter out, HttpSession session)
            throws IOException, ServletException {
        generateCommonHeader("Login", request, response, out, session);

        String userName = request.getParameter("username");
        if (userName != null) {
            session.setAttribute("username", userName);
            out.println("Now logged in!!");
            out.println("<script language=\"JavaScript\">");
            out
                    .println("function reload() { window.location=\"?action=auctionlist\" }");
            out.println("setTimeout(\"reload()\", 1000);");
            out.println("</script>");
        } else {
            out.print("<form action=\"");
            out.print(response.encodeURL(""));
            out.print("\" ");
            out.println("method=GET>");
            out.println("Username:");
            out.println("<input type=text size=20 name=username>");
            out.println("<input type=submit value=Login>");
            out.println("</form>");
        }

        generateCommonFooter(request, response, out, session, null, 0);
    }

    private void doLogout(HttpServletRequest request,
            HttpServletResponse response, PrintWriter out, HttpSession session)
            throws IOException, ServletException {
        generateCommonHeader("Logout", request, response, out, session);

        // session.invalidate();
        session.setAttribute("username", "");
        out.println("Now logged out!!");

        generateCommonFooter(request, response, out, session, null, 0);
    }

    private void doAuctionList(HttpServletRequest request,
            HttpServletResponse response, PrintWriter out, HttpSession session)
            throws IOException, ServletException {
        BidClient client = new BidClient();
        client.init();

        BidServerConnection conn = client.connect();
        
        generateCommonHeader("Auction List", request, response, out, session);
        
        LinkedList<Integer> items = client.getItemIds(conn);

        out.println("<script language=\"JavaScript\">");
        out.println("function reload() { window.location=\"?action=auctionlist\" }");
        out.println("setTimeout(\"reload()\", 2000);");
        out.println("</script>");
 
        out.println("<table border=2 width=100%>");
        out.println("<thead>");
        out.println("<tr>");
        out.println("<th>Title</th>");
        out.println("<th>End Time</th>");
        out.println("<th>High Bidder</th>");
        out.println("<th>High Bid</th>");
        
        out.println("</tr>");
        out.println("</thead>");
        
        out.println("<tbody>");

        for (Iterator<Integer> it = items.iterator(); it.hasNext(); )
        {
            Integer l = it.next();
            int id = l.intValue();
            out.println("<tr>");
            ItemInfo itemInfo = client.getItemInfo(conn, id);
            Bid topBid = client.getItemTopBid(conn, id);

            out.println("<tr>");
            out.println("<td><a href=\"?action=detail&id=" +id +"\">" + itemInfo.itemTitle + "</a></td>");
            out.println("<td>" + itemInfo.auctionEndTime + "</td>");
            if (topBid == null)
            {
                out.println("<td>none</td>");
                out.println("<td>none</td>");
            }
            else
            {
                out.println("<td>" + topBid.bidder + "</td>");
                out.println("<td>$" + topBid.bid/1000.0 + "</td>");
            }
            out.println("</tr>");
        }
        out.println("</tbody>");
        out.println("</table>");

        client.disconnect(conn);

        generateCommonFooter(request, response, out, session, conn.name, conn.port);
    }
    

    private void doDetail(HttpServletRequest request,
            HttpServletResponse response, PrintWriter out, HttpSession session)
            throws IOException, ServletException {
        int id = Integer.valueOf(request.getParameter("id"));
        
        String action = request.getParameter("action");

        BidClient client = new BidClient();
        client.init();

        BidServerConnection conn = client.connect();

        ItemInfo itemInfo = client.getItemInfo(conn, id);
       
        if (action.equals("place"))
        {
            int amount = Math.round(Float.valueOf(request.getParameter("amount"))) * 1000;
            String bidder = (String) session.getAttribute("username");
            client.placeBid(conn, id, amount, bidder, new Date());
        }

        generateCommonHeader("Detail: " + itemInfo.itemTitle, request, response, out, session);

        out.println("<script language=\"JavaScript\">");
        out.println("function reload() { window.location=\"?action=detail&id="+id+"\" }");
        out.println("setTimeout(\"reload()\", 5000);");
        out.println("</script>");

        out.print("<br/>Bid Server: " + conn.name+ ":" + conn.port + "<br/>");
 
        out.println("Item ID: " + id + "<br/>");
        out.println("Item Title: " + itemInfo.itemTitle + "<br/>");
        out.println("Item Description: " + itemInfo.itemDesc + "<br/>");
        out.println("End Time: " + itemInfo.auctionEndTime + "<br/><br/><br/>");
        
        LinkedList<Bid> bids = client.getBids(conn, id);

        out.print("<form action=\"");
        out.print(response.encodeURL(""));
        out.print("\" ");
        out.println("method=GET>");
        out.println("Place Bid:");
        out.println("<input type=hidden name=action value=place>");
        out.println("<input type=hidden name=id value="+id+">");
        double topBid = 0;
        if (!bids.isEmpty())
        {
            Bid top = bids.get(bids.size() - 1);
            topBid = top.bid/1000.0;
        }
        topBid += 1.0;

        out.println("<input type=text size=5 name=amount value=" + topBid + ">");
        out.println("<input type=submit value=Bid>");
        out.println("</form><br/>");
 

        out.println("Bid History: " + bids.size() + " total bids. <br/>" );
        out.println("<table border=2 width=100%>");
        out.println("<thead>");
        out.println("<tr>");
        out.println("<th>Bid</th>");
        out.println("<th>Bidder</th>");
        out.println("<th>Bid Time</th>");        
        out.println("</tr>");
        out.println("</thead>");
       
        out.println("<tbody>");
        ListIterator<Bid> it = bids.listIterator(bids.size());
        for (; it.hasPrevious(); )
        {
            Bid bid = it.previous();
            out.println("<tr>");
            out.println("<td>$" + bid.bid/1000.0 + "</td>");
            out.println("<td>" + bid.bidder + "</td>");
            out.println("<td>" + bid.bidTime + "</td>");
            out.println("</tr>");
        }
        out.println("</tbody>");
        out.println("</table>");
        
        client.disconnect(conn);
        
        generateCommonFooter(request, response, out, session, conn.name, conn.port);

    }
    
    
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        String action = request.getParameter("action");

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        HttpSession session = request.getSession(true);
        String userName = (String) session.getAttribute("username");

        if (action == null || userName == null) {
            action = "login";
            userName = "";
        }

        if (action.equals("logout")) {
            doLogout(request, response, out, session);
        } else if (userName.equals("") || action.equals("login")) {
            doLogin(request, response, out, session);
        } else if (action.equals("auctionlist")) {
            doAuctionList(request, response, out, session);
        } else if (action.equals("detail")) {
            doDetail(request, response, out, session);
        } else if (action.equals("place")) {
            doDetail(request, response, out, session);
        } 
    }
}
